package com.cj.service;

import com.cj.dao.CourseDao;
import com.cj.dao.CourseUserDao;
import com.cj.dao.UserDao;
import com.cj.entity.Course;
import com.cj.entity.CourseUser;
import com.cj.entity.PageBean;
import com.cj.entity.User;

import java.util.List;

/**
 * @Auther: chenjie
 * @Date: 2021/7/12 - 07 - 12 - 17:20
 * @Description: com.cj.service
 */
public class CourseUserService {
    CourseUserDao dao = new CourseUserDao();
    UserDao userDao =  new UserDao();
    CourseDao courseDao =  new CourseDao();

    public PageBean<CourseUser> findPages(String currentPage, String pageSize) {
        int cPage = Integer.parseInt(currentPage);
        int size = Integer.parseInt(pageSize);
        PageBean<CourseUser> pb = new PageBean<>();
        pb.setCurrentPage(cPage);
        pb.setPageSize(size);

        String sql = "select * from course_user";
        int totalCount = dao.getEntities(sql,CourseUser.class).size();
        pb.setTotalCount(totalCount);
        int totalPage = totalCount%size==0? totalCount/size : totalCount/size+1;
        pb.setTotalPage(totalPage);

        sql ="select * from course_user limit ?,?";
        List<CourseUser> courseUserList = dao.getEntities(sql, CourseUser.class,(cPage-1)*size,size);
        for (CourseUser courseUser : courseUserList) {
            User user = userDao.getEntity("select * from user where uid = ?", User.class, courseUser.getUid());
            courseUser.setUser(user);
            Course course = courseDao.getEntity("select * from course where cid =?", Course.class, courseUser.getCid());
            courseUser.setCourse(course);
        }
        pb.setList(courseUserList);

        return pb;
    }

    public int updateCourseUser(CourseUser c) {
        return dao.update("update course_user set cid=?,uid=? where id=?", c.getCid(), c.getUid(), c.getId());
    }

    public int deleteCourseUser(String ids) {
        String sql = "delete from course_user where id in ("+ids+")";
        return dao.update(sql);

    }

    public int insertCourseUser(String cid, String uid) {
        String sql = "insert into course_user values(null,?,?)";
        return dao.update(sql, cid, uid);
    }

    public CourseUser findCourseUser(String cid, String uid) {
        String sql = "select * from course_user where cid=? and uid=?";
        return dao.getEntity(sql, CourseUser.class, cid, uid);
    }
}
